package com.jn.erp.web.api.common.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.jn.erp.common.constant.Constants;
import com.jn.erp.common.constant.HttpStatus;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.core.page.TableDataInfo;
import com.jn.erp.common.exception.ServiceException;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.security.entity.LoginBody;
import com.jn.erp.security.entity.SysPermission;
import com.jn.erp.security.entity.SysUser;
import com.jn.erp.security.service.SysPermissionService;
import com.jn.erp.security.sysservice.SysUserService;
import com.jn.erp.security.utils.SecurityUtils;
import com.jn.erp.web.security.SysLoginService;
import com.jn.erp.web.api.sys.entity.SysOrg;
import com.jn.erp.web.api.sys.service.SysOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/8/28 14:08
 */
@RestController
public class CommonController extends BaseWebAuthController {


    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private com.jn.erp.security.sysservice.SysPermissionService menuService;
    /**
     * 机构信息
     */
    @PostMapping("/deptList")
    public TableDataInfo deptList() {
        List<SysOrg> deptCacheAll = sysOrgService.getDeptCacheAll();
        List<SysOrg> list = deptCacheAll.stream().filter(org->org.getPid()==0l||org.getPid()==1l).map(o -> {
            if (o.getPid() == 0l) {
                o.setName("运维登录");
            }
            return o;
        }).sorted(Comparator.comparing(SysOrg::getSortNum)).collect(Collectors.toList());
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),loginBody.getOrgId());
        String orgId = loginBody.getOrgId();
        if(StrUtil.isBlank(orgId)){
            throw new ServiceException("请求方式有误！请正确登录平台");
        }
        SysUser user =new SysUser();
        user.setName(loginBody.getUsername());
        user.setOrgId(Long.valueOf(orgId));
        SysUser sysUser = sysUserService.checkUserInDept(user);
        if(sysUser==null){
            throw new ServiceException("机构下没有该用户权限");
        }
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = sysPermissionService.getRolePermission(user);
//        // 权限集合
        Set<String> permissions = sysPermissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysPermission> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
